package com.server.push;

import com.alibaba.fastjson2.JSON;
import com.server.http.service.MobileAppService;
import com.server.libs.login.AppOline;
import com.server.libs.login.data.AppCache;
import com.server.pojo.MobileApp;
import com.server.push.mqtt.MqttMobileAppController;
import com.server.push.mqtt.base.Topic;
import com.server.push.mqtt.config.MqttGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class OnlinePush {

    @Autowired
    MqttGateway mqttGateway;

    @Autowired
    MobileAppService mobileAppService;
    @Autowired
    AppOline appOline;

    public void send(MobileApp mobileApp, Object data){
        AppCache cache = mobileAppService.getCache(mobileApp.getId());
        // 登录 && 在线
        if (cache!=null && appOline.isOline(mobileApp.getId())) {
            String topic = Topic.setTopic(MqttMobileAppController.client, "auth", cache.auth);
            mqttGateway.send(topic, JSON.toJSONString(data));
        }
    }

    public void send(List<MobileApp> mobileApps, Object data){
        for (MobileApp mobileApp : mobileApps) {
            AppCache cache = mobileAppService.getCache(mobileApp.getId());

            // 登录 && 在线
            if (cache!=null && appOline.isOline(mobileApp.getId())) {
                String topic = Topic.setTopic(MqttMobileAppController.client, "auth", cache.auth);
                mqttGateway.send(topic, JSON.toJSONString(data));
            }
        }
    }

}
